package cn.codepandas.unifiedresponse.config;

import cn.codepandas.unifiedresponse.annotation.UnifiedResponse;
import cn.codepandas.unifiedresponse.constant.Constants;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 向包含 UnifiedResponse 注解的响应添加标记
 *
 * @author Amaris
 * @since 1.0.0
 */
@Component
public class UnifiedResponseHandleInterceptor implements HandlerInterceptor {

    /**
     * 如果类或方法包含 UnifiedResponse 注解，则添加一个标记
     * @param request request
     * @param response response
     * @param handler handler
     * @return 预处理操作是否成功
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        if(handler instanceof HandlerMethod) {
            final HandlerMethod handlerMethod = (HandlerMethod) handler;
            final Class<?> targetClass = handlerMethod.getBeanType();
            final Method method = handlerMethod.getMethod();
            if(targetClass.isAnnotationPresent(UnifiedResponse.class)){
                request.setAttribute(Constants.TAG, targetClass.getAnnotation(UnifiedResponse.class));
            }else if(method.isAnnotationPresent(UnifiedResponse.class)){
                request.setAttribute(Constants.TAG, method.getAnnotation(UnifiedResponse.class));
            }
        }
        return true;
    }

}
